import { axisColorConfig } from '@/config/stage-canvas-config';
import { getDirectoryByPlankFace } from '@/utils';
import { Vector3 } from 'three';
import {
  Basis,
  Face,
  basis2AxisMap,
  basis2FaceMap,
  faceEnums,
} from '../constants';
import { PointObj2, PointObj3 } from '@/types';
import { Axis, FormValue } from '../types';
import { merge } from 'lodash-es';

export type BasisValueMap = Record<Basis, number>;

export function getBasisValueMap({
  width,
  height,
}: {
  width: number;
  height: number;
}): BasisValueMap {
  const halfW = height / 2;
  const halfH = width / 2;
  const basisValueMap = {
    [Basis.Front]: halfH,
    [Basis.Back]: -halfH,
    [Basis.Left]: -halfW,
    [Basis.Right]: halfW,
  };
  return basisValueMap;
}

export function getPointInBasis({
  point,
  basis,
  basisValueMap,
}: {
  point: PointObj2;
  basis: { x: Basis; y: Basis };
  basisValueMap: BasisValueMap;
}) {
  return {
    pointInBasisX: { x: point.x, y: basisValueMap[basis.x] },
    pointInBasisY: { x: basisValueMap[basis.y], y: point.y },
  };
}

export function getBasisArrowParams({
  basis,
  basisValueMap,
}: {
  basis: Basis;
  basisValueMap: BasisValueMap;
}) {
  const face = basis2FaceMap.get(basis)!;
  const direction = getDirectoryByPlankFace(face, Vector3);
  direction.negate();

  const axis = basis2AxisMap.get(basis)! as Axis;
  const color = axisColorConfig[axis];
  const positionObj = merge(
    { x: 0, y: 0, z: 0 },
    { [exchangeXYAxis(axis)]: basisValueMap[basis] },
  );
  const position = new Vector3(positionObj.x, positionObj.y, positionObj.z);
  // console.log({ basis, direction, position });
  if (basis === Basis.Left || basis === Basis.Right) {
    position.x = -position.x;
  }
  return { position, direction, color };
}

function exchangeXYAxis(axis: Axis) {
  return {
    x: 'y',
    y: 'x',
    z: 'z',
  }[axis];
}
